<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="网络编程,Linux环境编程,">





  <link rel="alternate" href="/atom.xml" title="恋恋风辰的个人博客" type="application/atom+xml">






<meta name="description" content="libevent中提供了一个Hello-world.c 的例子，从这个例子可以学习libevent是如何使用bufferevent的。这个例子在Sample中这个例子之前讲解过，这次主要看下bufferevent的使用。">
<meta name="keywords" content="网络编程,Linux环境编程">
<meta property="og:type" content="article">
<meta property="og:title" content="Libevent学习笔记(五) 根据例子学习bufferevent">
<meta property="og:url" content="http://www.limerence2017.com/2017/08/04/Libevent5/index.html">
<meta property="og:site_name" content="恋恋风辰的个人博客">
<meta property="og:description" content="libevent中提供了一个Hello-world.c 的例子，从这个例子可以学习libevent是如何使用bufferevent的。这个例子在Sample中这个例子之前讲解过，这次主要看下bufferevent的使用。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://www.limerence2017.com/2017/08/04/Libevent5/Libevent5/1.png">
<meta property="og:updated_time" content="2020-06-22T09:30:58.699Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Libevent学习笔记(五) 根据例子学习bufferevent">
<meta name="twitter:description" content="libevent中提供了一个Hello-world.c 的例子，从这个例子可以学习libevent是如何使用bufferevent的。这个例子在Sample中这个例子之前讲解过，这次主要看下bufferevent的使用。">
<meta name="twitter:image" content="http://www.limerence2017.com/2017/08/04/Libevent5/Libevent5/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.limerence2017.com/2017/08/04/Libevent5/">





  <title>Libevent学习笔记(五) 根据例子学习bufferevent | 恋恋风辰的个人博客</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">恋恋风辰的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.limerence2017.com/2017/08/04/Libevent5/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="恋恋风辰">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="恋恋风辰的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Libevent学习笔记(五) 根据例子学习bufferevent</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-08-04T17:41:54+08:00">
                2017-08-04
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/netprogram/" itemprop="url" rel="index">
                    <span itemprop="name">网络编程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>libevent中提供了一个Hello-world.c 的例子，从这个例子可以学习libevent是如何使用bufferevent的。<br>这个例子在Sample中<br><img src="Libevent5/1.png" alt="1"><br>这个例子之前讲解过，这次主要看下bufferevent的使用。<br><a id="more"></a></p>
<h2 id="第一步找到main函数"><a href="#第一步找到main函数" class="headerlink" title="第一步找到main函数"></a>第一步找到main函数</h2><p>main函数</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">   <span class="comment">//...</span></span><br><span class="line">listener = evconnlistener_new_bind(base, listener_cb, (<span class="keyword">void</span> *)base,</span><br><span class="line">        LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, <span class="number">-1</span>,</span><br><span class="line">        (struct sockaddr*)&amp;<span class="built_in">sin</span>,</span><br><span class="line">        <span class="keyword">sizeof</span>(<span class="built_in">sin</span>));</span><br><span class="line"></span><br><span class="line"> <span class="comment">//...</span></span><br><span class="line"></span><br><span class="line">　　　　event_base_dispatch(base);</span><br><span class="line"></span><br><span class="line">　　　　evconnlistener_free(listener);</span><br><span class="line">　　　　event_free(signal_event);</span><br><span class="line">　　　　event_base_free(base);</span><br><span class="line"></span><br><span class="line">　　　　<span class="built_in">printf</span>(<span class="string">"done\n"</span>);</span><br><span class="line">　　　　<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>main函数中调用evconnlistener_new_bind()创建了一个evconnlistener 类型的listener,然后拍发消息，之后释放各种资源。</p>
<h2 id="第二步在evconnlistener-new-bind-中调用evconnlistener-new-完成listener属性设置。"><a href="#第二步在evconnlistener-new-bind-中调用evconnlistener-new-完成listener属性设置。" class="headerlink" title="第二步在evconnlistener_new_bind()中调用evconnlistener_new()完成listener属性设置。"></a>第二步在evconnlistener_new_bind()中调用evconnlistener_new()完成listener属性设置。</h2><p>这个函数里对evconnlistener_event中base进行回调函数的绑定和参数设置，通过event_assign将evconnlistener_event的istener设置读事件的回调函数，并且通过evconnlistener_enable让读回调函数触发，也就是触发listener_read_cb。这里evconnlister_enable调用的也是结构体注册的enable具体看代码吧，调用的是r = lev-&gt;ops-&gt;enable(lev);等同于调用event_listener_enable，该函数内部完成event_add。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">evconnlistener_event</span> &#123;</span></span><br><span class="line">　　　　<span class="class"><span class="keyword">struct</span> <span class="title">evconnlistener</span> <span class="title">base</span>;</span></span><br><span class="line">　　　　<span class="class"><span class="keyword">struct</span> <span class="title">event</span> <span class="title">listener</span>;</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">evconnlistener</span> *</span></span><br><span class="line"><span class="class"><span class="title">evconnlistener_new</span>(<span class="title">struct</span> <span class="title">event_base</span> *<span class="title">base</span>,</span></span><br><span class="line"><span class="class">    <span class="title">evconnlistener_cb</span> <span class="title">cb</span>, <span class="title">void</span> *<span class="title">ptr</span>, <span class="title">unsigned</span> <span class="title">flags</span>, <span class="title">int</span> <span class="title">backlog</span>,</span></span><br><span class="line"><span class="class">    <span class="title">evutil_socket_t</span> <span class="title">fd</span>)</span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">evconnlistener_event</span> *<span class="title">lev</span>;</span><span class="comment">//开辟evconnlistener_event大小区域</span></span><br><span class="line">    lev = mm_calloc(<span class="number">1</span>, <span class="keyword">sizeof</span>(struct evconnlistener_event));</span><br><span class="line">    <span class="keyword">if</span> (!lev)</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">    <span class="comment">//lev -&gt; base 表示  evconnlistener </span></span><br><span class="line">    <span class="comment">//evconnlistener     evconnlistener_ops 基本回调参数和回调函数结构体赋值</span></span><br><span class="line">    lev-&gt;base.ops = &amp;evconnlistener_event_ops;</span><br><span class="line">    <span class="comment">//evconnlistener_cb 设置为listener_cb</span></span><br><span class="line">    lev-&gt;base.cb = cb;</span><br><span class="line">    <span class="comment">//ptr表示event_base 指针</span></span><br><span class="line">    lev-&gt;base.user_data = ptr;</span><br><span class="line">    lev-&gt;base.flags = flags;</span><br><span class="line">    lev-&gt;base.refcnt = <span class="number">1</span>;<span class="comment">//  lev   is evconnlistener_event       </span></span><br><span class="line">    <span class="comment">//lev-&gt;listener is event</span></span><br><span class="line">    <span class="comment">//为lev-&gt;listener设置读回调函数和读关注事件，仅进行设置并没加入event队列</span></span><br><span class="line">    event_assign(&amp;lev-&gt;listener, base, fd, EV_READ|EV_PERSIST,</span><br><span class="line">        listener_read_cb, lev);</span><br><span class="line">    <span class="comment">//实际调用了event_add将事件加入event队列</span></span><br><span class="line">    evconnlistener_enable(&amp;lev-&gt;base);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> &amp;lev-&gt;base;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="第三步listener-read-cb内部调用accept生成新的socket处理连接，调用listener-cb"><a href="#第三步listener-read-cb内部调用accept生成新的socket处理连接，调用listener-cb" class="headerlink" title="第三步listener_read_cb内部调用accept生成新的socket处理连接，调用listener_cb"></a>第三步listener_read_cb内部调用accept生成新的socket处理连接，调用listener_cb</h2><p>新的socket作为参数传递给evconnlistener_event中base的回调函数listener_cb</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">void</span></span><br><span class="line">listener_read_cb(<span class="keyword">evutil_socket_t</span> fd, <span class="keyword">short</span> what, <span class="keyword">void</span> *p)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">evconnlistener</span> *<span class="title">lev</span> = <span class="title">p</span>;</span></span><br><span class="line">    <span class="keyword">int</span> err;</span><br><span class="line">    evconnlistener_cb cb;</span><br><span class="line">    evconnlistener_errorcb errorcb;</span><br><span class="line">    <span class="keyword">void</span> *user_data;</span><br><span class="line">    LOCK(lev);</span><br><span class="line">    <span class="keyword">while</span> (<span class="number">1</span>) &#123;</span><br><span class="line">      　　<span class="comment">//...//cb 就 是  listener_cb</span></span><br><span class="line">        cb = lev-&gt;cb;</span><br><span class="line">        user_data = lev-&gt;user_data;</span><br><span class="line">        UNLOCK(lev);</span><br><span class="line">        <span class="comment">//触发了listener_cb</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">//完成了eventbuffer注册写和事件函数  </span></span><br><span class="line">        cb(lev, new_fd, (struct sockaddr*)&amp;ss, (<span class="keyword">int</span>)socklen,</span><br><span class="line">            user_data);</span><br><span class="line">        </span><br><span class="line">        LOCK(lev);</span><br><span class="line">        <span class="keyword">if</span> (lev-&gt;refcnt == <span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">int</span> freed = listener_decref_and_unlock(lev);</span><br><span class="line">            EVUTIL_ASSERT(freed);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        --lev-&gt;refcnt;</span><br><span class="line">    &#125;</span><br><span class="line">  <span class="comment">//...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="第四步listener-cb-调用bufferevent-socket-new-生成bufferevent，"><a href="#第四步listener-cb-调用bufferevent-socket-new-生成bufferevent，" class="headerlink" title="第四步listener_cb 调用bufferevent_socket_new 生成bufferevent，"></a>第四步listener_cb 调用bufferevent_socket_new 生成bufferevent，</h2><p>然后bufferevent_setcb设置读写水位触发的回调函数，bufferevent_enable将bufferevent的写事件加入监听，即开始检测写事件。关闭读事件，并且向outbuf中写入MSG<br>bufferevent_socket_new内部绑定bufferevent的读写事件回调函数，读事件为bufev-&gt;ev_read，绑定了bufferevent_readcb回调函数，<br>写事件为bufev-&gt;ev_write，<br>绑定了bufferevent_writecb回调函数。这两个回调函数和bufferevent的readcb和writecb是不一样的，这两个函数在对应的读写事件激活时才触发。<br>而readcb和writecb是基于水位线达到阈值才会触发。做好区分。bufferevent_socket_new内部还对bufev-&gt;output添加了对调函数bufferevent_socket_outbuf_cb，<br>bufferevent_socket_outbuf_cb内部检测是否开启写事件，以及是否可写，如果可写，同样将写事件加入监听队列，也就是调用了event_add。<br>bufferevent_socket_new内部解释完毕了。bufferevent_setcb设置的是读写水位达到阈值后的回调函数，<br>bufferevent_enable内部也是调用了event_add，将读事件加入监听队列。<br>bufferevent_enable内部调用bufev-&gt;be_ops-&gt;enable(bufev, impl_events)，等同于be_socket_enable，另外bufferevent_write函数内部调用evbuffer_add，<br>evbuffer_add内部调用了evbuffer_invoke_callbacks，就会调用绑定在output buffer上的回调函数bufferevent_socket_outbuf_cb。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">void</span></span><br><span class="line">listener_cb(struct evconnlistener *listener, <span class="keyword">evutil_socket_t</span> fd,</span><br><span class="line">    struct sockaddr *sa, <span class="keyword">int</span> socklen, <span class="keyword">void</span> *user_data)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">event_base</span> *<span class="title">base</span> = <span class="title">user_data</span>;</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">bufferevent</span> *<span class="title">bev</span>;</span></span><br><span class="line"></span><br><span class="line">    bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);</span><br><span class="line">    <span class="keyword">if</span> (!bev) &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">"Error constructing bufferevent!"</span>);</span><br><span class="line">        event_base_loopbreak(base);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//设置写回调和事件回调</span></span><br><span class="line">    bufferevent_setcb(bev, <span class="literal">NULL</span>, conn_writecb, conn_eventcb, <span class="literal">NULL</span>);</span><br><span class="line">    bufferevent_enable(bev, EV_WRITE);</span><br><span class="line">    bufferevent_disable(bev, EV_READ);</span><br><span class="line">    <span class="comment">//将要发送的内容写入evbuffer结构</span></span><br><span class="line">    bufferevent_write(bev, MESSAGE, <span class="built_in">strlen</span>(MESSAGE));</span><br><span class="line">&#125;</span><br><span class="line">``` cpp</span><br><span class="line"> </span><br><span class="line">``` cpp</span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">bufferevent</span> *</span></span><br><span class="line"><span class="class"><span class="title">bufferevent_socket_new</span>(<span class="title">struct</span> <span class="title">event_base</span> *<span class="title">base</span>, <span class="title">evutil_socket_t</span> <span class="title">fd</span>,</span></span><br><span class="line"><span class="class">    <span class="title">int</span> <span class="title">options</span>)</span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">bufferevent_private</span> *<span class="title">bufev_p</span>;</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">bufferevent</span> *<span class="title">bufev</span>;</span></span><br><span class="line"></span><br><span class="line">　　<span class="comment">//...//设置bufferevent中   ev_read(event类型)回调函数</span></span><br><span class="line">    event_assign(&amp;bufev-&gt;ev_read, bufev-&gt;ev_base, fd,</span><br><span class="line">        EV_READ|EV_PERSIST, bufferevent_readcb, bufev);</span><br><span class="line">    <span class="comment">//设置bufferevent中   ev_write(event类型)回调函数</span></span><br><span class="line">    event_assign(&amp;bufev-&gt;ev_write, bufev-&gt;ev_base, fd,</span><br><span class="line">        EV_WRITE|EV_PERSIST, bufferevent_writecb, bufev);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//为bufev-&gt;output(evbuffer类型)设置回调函数，插入bufferevent-&gt;output的callback队列</span></span><br><span class="line">    <span class="comment">//bufferevent_socket_outbuf_cb回调函数内部将ev_write事件加入事件队列</span></span><br><span class="line">    evbuffer_add_cb(bufev-&gt;output, bufferevent_socket_outbuf_cb, bufev);</span><br><span class="line"></span><br><span class="line">    evbuffer_freeze(bufev-&gt;input, <span class="number">0</span>);</span><br><span class="line">    evbuffer_freeze(bufev-&gt;output, <span class="number">1</span>);</span><br><span class="line">  　　<span class="comment">//...</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> bufev;</span><br><span class="line">&#125;</span><br><span class="line">``` </span><br><span class="line">``` cpp</span><br><span class="line"><span class="keyword">static</span> <span class="keyword">int</span></span><br><span class="line">be_socket_enable(struct bufferevent *bufev, <span class="keyword">short</span> event)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">if</span> (event &amp; EV_READ) &#123;</span><br><span class="line">        <span class="keyword">if</span> (be_socket_add(&amp;bufev-&gt;ev_read,&amp;bufev-&gt;timeout_read) == <span class="number">-1</span>)</span><br><span class="line">            <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (event &amp; EV_WRITE) &#123;</span><br><span class="line">        <span class="keyword">if</span> (be_socket_add(&amp;bufev-&gt;ev_write,&amp;bufev-&gt;timeout_write) == <span class="number">-1</span>)</span><br><span class="line">            <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="第五步-bufferevent的output中写入MSG，-并且之前也已经将EV-WRITE事件加入监听，所以内核检测到socket可写，会通知bufferevent的ev-write，调用绑定在ev-write上的函数bufferevent-writecb。"><a href="#第五步-bufferevent的output中写入MSG，-并且之前也已经将EV-WRITE事件加入监听，所以内核检测到socket可写，会通知bufferevent的ev-write，调用绑定在ev-write上的函数bufferevent-writecb。" class="headerlink" title="第五步 bufferevent的output中写入MSG， 并且之前也已经将EV_WRITE事件加入监听，所以内核检测到socket可写，会通知bufferevent的ev_write，调用绑定在ev_write上的函数bufferevent_writecb。"></a>第五步 bufferevent的output中写入MSG， 并且之前也已经将EV_WRITE事件加入监听，所以内核检测到socket可写，会通知bufferevent的ev_write，调用绑定在ev_write上的函数bufferevent_writecb。</h2><p>这是bufferevent内部的写操作，我们可以详细看一下。之前也有讲过bufferevent会将接收到的数据放到inputbuffer中，将outputbuffer中的数据发送。所以之前讲过的接口bufferevent_write让我们将要发送的数据放到output中，bufferevent_read可以从input中读出bufferevent接收到的数据。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">void</span></span><br><span class="line">bufferevent_writecb(<span class="keyword">evutil_socket_t</span> fd, <span class="keyword">short</span> event, <span class="keyword">void</span> *arg)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">bufferevent</span> *<span class="title">bufev</span> = <span class="title">arg</span>;</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">bufferevent_private</span> *<span class="title">bufev_p</span> =</span></span><br><span class="line"><span class="class">        <span class="title">EVUTIL_UPCAST</span>(<span class="title">bufev</span>, <span class="title">struct</span> <span class="title">bufferevent_private</span>, <span class="title">bev</span>);</span></span><br><span class="line">    <span class="keyword">int</span> res = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">short</span> what = BEV_EVENT_WRITING;</span><br><span class="line">    <span class="keyword">int</span> connected = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">ev_ssize_t</span> atmost = <span class="number">-1</span>;</span><br><span class="line">    <span class="comment">//对 bufferevent加锁，支持多线程安全模式</span></span><br><span class="line">    _bufferevent_incref_and_lock(bufev);</span><br><span class="line">    <span class="comment">//检测是否带有超时事件</span></span><br><span class="line">    <span class="keyword">if</span> (event == EV_TIMEOUT) &#123;</span><br><span class="line">        <span class="comment">/* Note that we only check for event==EV_TIMEOUT. If</span></span><br><span class="line"><span class="comment">         * event==EV_TIMEOUT|EV_WRITE, we can safely ignore the</span></span><br><span class="line"><span class="comment">         * timeout, since a read has occurred */</span></span><br><span class="line">        what |= BEV_EVENT_TIMEOUT;</span><br><span class="line">        <span class="keyword">goto</span> error;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//判断是否是连接事件</span></span><br><span class="line">    <span class="keyword">if</span> (bufev_p-&gt;connecting) &#123;</span><br><span class="line">        <span class="keyword">int</span> c = evutil_socket_finished_connecting(fd);</span><br><span class="line">        <span class="comment">/* we need to fake the error if the connection was refused</span></span><br><span class="line"><span class="comment">         * immediately - usually connection to localhost on BSD */</span></span><br><span class="line">        <span class="keyword">if</span> (bufev_p-&gt;connection_refused) &#123;</span><br><span class="line">          bufev_p-&gt;connection_refused = <span class="number">0</span>;</span><br><span class="line">          c = <span class="number">-1</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (c == <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">goto</span> done;</span><br><span class="line"></span><br><span class="line">        bufev_p-&gt;connecting = <span class="number">0</span>;</span><br><span class="line">        <span class="comment">//连接失败删除该事件</span></span><br><span class="line">        <span class="keyword">if</span> (c &lt; <span class="number">0</span>) &#123;</span><br><span class="line">            event_del(&amp;bufev-&gt;ev_write);</span><br><span class="line">            event_del(&amp;bufev-&gt;ev_read);</span><br><span class="line">            _bufferevent_run_eventcb(bufev, BEV_EVENT_ERROR);</span><br><span class="line">            <span class="keyword">goto</span> done;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            connected = <span class="number">1</span>;</span><br><span class="line">            <span class="comment">//windows情况下直接运行事件回调函数，然后go done</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifdef</span> WIN32</span></span><br><span class="line">            <span class="keyword">if</span> (BEV_IS_ASYNC(bufev)) &#123;</span><br><span class="line">                event_del(&amp;bufev-&gt;ev_write);</span><br><span class="line">                bufferevent_async_set_connected(bufev);</span><br><span class="line">                _bufferevent_run_eventcb(bufev,</span><br><span class="line">                        BEV_EVENT_CONNECTED);</span><br><span class="line">                <span class="keyword">goto</span> done;</span><br><span class="line">            &#125;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line">    <span class="comment">//linux 下 运行事件回调函数</span></span><br><span class="line">            _bufferevent_run_eventcb(bufev,</span><br><span class="line">                    BEV_EVENT_CONNECTED);</span><br><span class="line">        <span class="comment">//检测是否可写，不可写删除该事件</span></span><br><span class="line">            <span class="keyword">if</span> (!(bufev-&gt;enabled &amp; EV_WRITE) ||</span><br><span class="line">                bufev_p-&gt;write_suspended) &#123;</span><br><span class="line">                event_del(&amp;bufev-&gt;ev_write);</span><br><span class="line">                <span class="keyword">goto</span> done;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//计算bufferevent能写的最大数量</span></span><br><span class="line">    atmost = _bufferevent_get_write_max(bufev_p);</span><br><span class="line">    <span class="comment">//写事件挂起了，跳过。</span></span><br><span class="line">    <span class="keyword">if</span> (bufev_p-&gt;write_suspended)</span><br><span class="line">        <span class="keyword">goto</span> done;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//output非空</span></span><br><span class="line">    <span class="keyword">if</span> (evbuffer_get_length(bufev-&gt;output)) &#123;</span><br><span class="line">        <span class="comment">//将output的头打开，从头部发送</span></span><br><span class="line">        evbuffer_unfreeze(bufev-&gt;output, <span class="number">1</span>);</span><br><span class="line">        <span class="comment">//bufferevent调用写操作，将outbuffer中的内容发送出去</span></span><br><span class="line">        res = evbuffer_write_atmost(bufev-&gt;output, fd, atmost);</span><br><span class="line">        <span class="comment">//将output的头部关闭</span></span><br><span class="line">        evbuffer_freeze(bufev-&gt;output, <span class="number">1</span>);</span><br><span class="line">        <span class="keyword">if</span> (res == <span class="number">-1</span>) &#123;</span><br><span class="line">            <span class="keyword">int</span> err = evutil_socket_geterror(fd);</span><br><span class="line">            <span class="keyword">if</span> (EVUTIL_ERR_RW_RETRIABLE(err))</span><br><span class="line">                <span class="keyword">goto</span> reschedule;</span><br><span class="line">            what |= BEV_EVENT_ERROR;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (res == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">/* eof case</span></span><br><span class="line"><span class="comment">               XXXX Actually, a 0 on write doesn't indicate</span></span><br><span class="line"><span class="comment">               an EOF. An ECONNRESET might be more typical.</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">             <span class="comment">//写完了</span></span><br><span class="line">            what |= BEV_EVENT_EOF;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (res &lt;= <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">goto</span> error;</span><br><span class="line">        <span class="comment">//bufferevent减少发送的大小，留下未发送的，下次再发送，因为是PERSIST|WRITE</span></span><br><span class="line">        <span class="comment">//所以会在下次检测到可写时候继续写</span></span><br><span class="line">        _bufferevent_decrement_write_buckets(bufev_p, res);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//计算是否将outbuf中的内容发送完，发完了就删除写事件</span></span><br><span class="line">    <span class="keyword">if</span> (evbuffer_get_length(bufev-&gt;output) == <span class="number">0</span>) &#123;</span><br><span class="line">        event_del(&amp;bufev-&gt;ev_write);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">     * Invoke the user callback if our buffer is drained or below the</span></span><br><span class="line"><span class="comment">     * low watermark.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">     <span class="comment">//将buffer中的内容发完，或者低于low 水位，那么调用用户注册的写回调函数</span></span><br><span class="line">    <span class="comment">//之前注册在bufev-&gt;writecb中的回调函数</span></span><br><span class="line">    <span class="keyword">if</span> ((res || !connected) &amp;&amp;</span><br><span class="line">        evbuffer_get_length(bufev-&gt;output) &lt;= bufev-&gt;wm_write.low) &#123;</span><br><span class="line">        _bufferevent_run_writecb(bufev);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">goto</span> done;</span><br><span class="line"></span><br><span class="line"> reschedule:</span><br><span class="line">    <span class="keyword">if</span> (evbuffer_get_length(bufev-&gt;output) == <span class="number">0</span>) &#123;</span><br><span class="line">        event_del(&amp;bufev-&gt;ev_write);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">goto</span> done;</span><br><span class="line"></span><br><span class="line"> error:</span><br><span class="line">    bufferevent_disable(bufev, EV_WRITE);</span><br><span class="line">    _bufferevent_run_eventcb(bufev, what);</span><br><span class="line"></span><br><span class="line"> done:</span><br><span class="line">    _bufferevent_decref_and_unlock(bufev);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="第六步：这个函数内部每次尽可能多的发送数据，"><a href="#第六步：这个函数内部每次尽可能多的发送数据，" class="headerlink" title="第六步：这个函数内部每次尽可能多的发送数据，"></a>第六步：这个函数内部每次尽可能多的发送数据，</h2><p>没有发送完就下次轮询继续发送,直到水位低于或等于写数据的低水位，那么就会触发bufferevent低水位写回调函数。也就是conn_writecb，</p>
<p>在conn_writecb内部检测output buffer中数据为空，就释放该bufferevent。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">void</span></span><br><span class="line">conn_writecb(struct bufferevent *bev, <span class="keyword">void</span> *user_data)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">evbuffer</span> *<span class="title">output</span> = <span class="title">bufferevent_get_output</span>(<span class="title">bev</span>);</span></span><br><span class="line">    <span class="keyword">if</span> (evbuffer_get_length(output) == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">"flushed answer\n"</span>);</span><br><span class="line">        bufferevent_free(bev);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这就是整体流程，bufferevent内部的流畅看懂即可，我们只需要使用libevent提供的接口即可。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/网络编程/" rel="tag"># 网络编程</a>
          
            <a href="/tags/Linux环境编程/" rel="tag"># Linux环境编程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/04/neterror/" rel="next" title="网络编程的一些错误总结">
                <i class="fa fa-chevron-left"></i> 网络编程的一些错误总结
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/04/libevent4/" rel="prev" title="Libevent学习笔记(四) bufferevent 的 concepts and basics">
                Libevent学习笔记(四) bufferevent 的 concepts and basics <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">恋恋风辰</p>
              <p class="site-description motion-element" itemprop="description">重剑无锋，大巧不工</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">146</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/secondtonone1" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/wang-wu-chen-32/activities" target="_blank" title="ZhiHu">
                    
                      <i class="fa fa-fw fa-ZhiHu"></i>ZhiHu</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#第一步找到main函数"><span class="nav-number">1.</span> <span class="nav-text">第一步找到main函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#第二步在evconnlistener-new-bind-中调用evconnlistener-new-完成listener属性设置。"><span class="nav-number">2.</span> <span class="nav-text">第二步在evconnlistener_new_bind()中调用evconnlistener_new()完成listener属性设置。</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#第三步listener-read-cb内部调用accept生成新的socket处理连接，调用listener-cb"><span class="nav-number">3.</span> <span class="nav-text">第三步listener_read_cb内部调用accept生成新的socket处理连接，调用listener_cb</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#第四步listener-cb-调用bufferevent-socket-new-生成bufferevent，"><span class="nav-number">4.</span> <span class="nav-text">第四步listener_cb 调用bufferevent_socket_new 生成bufferevent，</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#第五步-bufferevent的output中写入MSG，-并且之前也已经将EV-WRITE事件加入监听，所以内核检测到socket可写，会通知bufferevent的ev-write，调用绑定在ev-write上的函数bufferevent-writecb。"><span class="nav-number">5.</span> <span class="nav-text">第五步 bufferevent的output中写入MSG， 并且之前也已经将EV_WRITE事件加入监听，所以内核检测到socket可写，会通知bufferevent的ev_write，调用绑定在ev_write上的函数bufferevent_writecb。</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#第六步：这个函数内部每次尽可能多的发送数据，"><span class="nav-number">6.</span> <span class="nav-text">第六步：这个函数内部每次尽可能多的发送数据，</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">恋恋风辰</span>

  
  
 
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
 
 
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.3</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
